package com.guigu.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guigu.CommodityService;
import com.guigu.ShoppingCartService;
import com.guigu.mapper.CommodityMapper;
import com.guigu.mapper.ShoppingCartMapper;
import com.guigu.pojo.Commodity;
import com.guigu.pojo.FrontShoppingCart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, FrontShoppingCart> implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private CommodityService commodityService;
    //查询用户id下的购物车
    @Override
    public PageInfo<FrontShoppingCart> selectPage(int pageNo, int pageSize,int uid) {
        PageHelper.startPage(pageNo, pageSize);
        List<FrontShoppingCart> frontShoppingCarts = shoppingCartMapper.selectPage(uid);
        PageInfo<FrontShoppingCart> frontShoppingCartPageInfo = new PageInfo<>(frontShoppingCarts);
        return frontShoppingCartPageInfo;
    }
    //新增购物车
    @Override
    public boolean InsertShoppingCart(int uid, int cid, int num) {
        // 根据商品id查询对应的商品
        Commodity commodity = commodityService.getById(cid);
        // 根据商品id和用户id查询购物车表中的数据
        QueryWrapper<FrontShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.eq("commodity_id",cid);
        wrapper.eq("user_id",uid);
        FrontShoppingCart one = this.getOne(wrapper);
        if(Objects.equals(null,one)){
        one=new FrontShoppingCart();
        one.setUserId(uid);
        one.setCommodityId(cid);
        one.setQuantity(num);
        one.setCreateTime(new Date());
        one.setSubtotal(commodity.getCommodityPrice()*num);
        one.setCheckTag(0);
        this.save(one);
        }else {
         //存在当前要添加的购物项，修改数量和小计
         one.setQuantity(one.getQuantity()+num);
         one.setSubtotal(one.getSubtotal()+commodity.getCommodityPrice()*num);
        this.updateById(one);
        }
        return true;
    }
    //更新购物车数量和小计
    @Override
    public boolean updateShoppingCart(int cid, int num) {
        // 根据cartId查找商品id
        FrontShoppingCart frontShoppingCart = this.getById(cid);
        // 根据商品id查询商品信息
        Commodity commodity = commodityService.getById(frontShoppingCart.getCommodityId());
        //更新数量
        frontShoppingCart.setQuantity(num);
        //更新小计
        frontShoppingCart.setSubtotal(commodity.getCommodityPrice()*num);
        return this.updateById(frontShoppingCart);
    }
}
